package com.sunrise.dispatcher.addressbook;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.vaadin.Application;
import com.vaadin.service.ApplicationContext;

@SuppressWarnings("serial")
public class AddressBookApplication extends Application implements ApplicationContext.TransactionListener {

	private static ThreadLocal<AddressBookApplication> currentApplication = new ThreadLocal<AddressBookApplication>();

	@Override
	public void init() {
		getContext().addTransactionListener(this);
		new ClassPathXmlApplicationContext("classpath*:META-INF/spring/applicationContext*.xml");
		setTheme("contacts");
		setMainWindow(new LoginWindow());
	}

	@Override
	public void transactionStart(Application application, Object transactionData) {
		if (application == AddressBookApplication.this) {
			currentApplication.set(this);
		}
	}

	@Override
	public void transactionEnd(Application application, Object transactionData) {
		if (application == AddressBookApplication.this) {
			currentApplication.set(null);
			currentApplication.remove();
		}
	}

	public static AddressBookApplication getInstance() {
		return currentApplication.get();
	}

	public void authenticate(String login, String password) throws Exception {
		if ("user".equals(login) && "querty".equals(password)) {
			loadProtectedResources();
			return;
		}

		throw new Exception("Login failed!");

	}

	private void loadProtectedResources() {
		setMainWindow(new AddressBookWindow("Address application demo"));
	}
}
